import { FC, useState, useEffect } from 'react';
import { Table, Space, Card, Form, Button, Select, Pagination, Popconfirm, message, Modal, Input, DatePicker } from 'antd';
import request from "umi-request";
import { format } from "../../../utils/time";

interface cityItemType {
  id: number;
  nm: string;
  py: string;
}
interface listType {
  admin: string;
  city: string;
  handleTime: string;
  openTime: string;
  operating: string;
  useCar: string;
  __v: number;
  _id: string;
}

const City: FC = () => {
  // 查询
  const [form] = Form.useForm();
  const [searchObj, setSearchObj] = useState({});
  const search = () => {
    console.log(form.getFieldsValue());
    setSearchObj(form.getFieldsValue());
  }
  const reset = () => {
    form.resetFields();
    setSearchObj({});
  }
  //获取城市列表
  const [cityList, setCityList] = useState<cityItemType[]>([]);
  useEffect(() => {
    getCityData();
  }, []);
  // 获取城市数据
  const getCityData = () => {
    request
      .get("http://pudge.wang:3000/api/cities/list")
      .then((response) => {
        setCityList(response.cts);
      })
  }
  // 获取列表数据
  const [list, setList] = useState<listType[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [total, setTotal] = useState(0);
  useEffect(() => {
    getListData();
  }, [currentPage, searchObj])
  const getListData = () => {
    request
      .post("http://pudge.wang:3000/api/cities/manage/list", {
        data: {
          page_size: 10,
          current_page: currentPage,
          ...searchObj,
        }
      })
      .then((response) => {
        const res = response.result.map((item: listType) => {
          return { ...item, key: item._id }
        });
        setList(res);
        setTotal(response.total);
      });
  }
  // 删除
  const remove = (list: listType) => {
    request
      .post("http://pudge.wang:3000/api/cities/manage/del", {
        data: {
          id: list._id
        }
      })
      .then((response) => {
        if (response.status === 0) {
          message.success('删除成功');
        } else {
          message.error(response.msg);
        }
      });
    getListData();

  }
  // 列表数据
  const columns = [
    {
      title: '城市ID',
      dataIndex: '_id',
    },
    {
      title: '城市名称',
      dataIndex: 'city',
    },
    {
      title: '用车模式',
      dataIndex: 'useCar',
      render(text: string) {
        return <span>{text === '1' ? "禁停区" : "停车点"}</span>
      }
    },
    {
      title: '运营模式',
      dataIndex: 'operating',
      render(text: string) {
        return <span>{text === '1' ? "直营" : "加盟"}</span>
      }
    },
    {
      title: '城市管理员',
      dataIndex: 'admin',
    },
    {
      title: '城市开通时间',
      dataIndex: 'openTime',
      // format
      render(text: string) {
        return <span>{format(Number(text))}</span>
      }
    },
    {
      title: "操作",
      render(text: string, record: listType) {
        return <Space>
          <Button type="primary" ghost>编辑</Button>
          <Popconfirm
            title="确定删除这条数据嘛?"
            onConfirm={() => remove(record)}
            okText="Yes"
            cancelText="No"
          >
            <Button danger>删除</Button>
          </Popconfirm>
        </Space>
      }
    }
  ];

  // 换页
  const changePage = (page: number) => {
    console.log(page);
    setCurrentPage(page);
  }

  // 新增弹出
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form2] = Form.useForm();
  // 点击新增
  const onOK = () => {
    setIsModalVisible(true);
  }
  const handleOk = () => {
    console.log(form2.validateFields());

    // 验证表单信息
    form2.validateFields().then(value => {
      console.log(value);
      request
        .post("http://pudge.wang:3000/api/cities/manage/add", {
          data: {
            ...value, openTime: new Date(value.openTime).getTime(), handleTime: new Date().getTime()
          }
        })
        .then((response) => {
          if (response.status === 0) {
            setIsModalVisible(false);
            message.success('添加成功');
            form2.resetFields();
          } else {
            message.error(response.msg);
          }
        });
      getListData();
    }).catch((err) => {
      console.log(err);
    })


  }
  const handleCancel = () => {
    setIsModalVisible(false);
  }
  const onFinish = (values: any) => {
    console.log('Success:', values);
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };
  return (
    <Space direction="vertical" style={{ width: "100%" }}>
      <Card>
        <Space>
          <Form form={form} name="horizontal_login" layout="inline" >
            <Form.Item
              name="city"
              label="城市"
            >
              <Select style={{ width: 120 }} allowClear>
                {
                  cityList.map((item) =>
                    <Select.Option key={item.id} value={item.nm}>{item.nm}</Select.Option>)
                }
              </Select>
            </Form.Item>
            <Form.Item
              name="useCar"
              label="用车模式"
            >
              <Select style={{ width: 120 }} allowClear>
                <Select.Option value="1">禁停区</Select.Option>
                <Select.Option value="2">停车点</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item
              name="operating"
              label="运营模式"
            >
              <Select style={{ width: 120 }} allowClear>
                <Select.Option value="1">直营</Select.Option>
                <Select.Option value="2">加盟</Select.Option>
              </Select>
            </Form.Item>
            <Space>
              <Button type='primary' onClick={search}>查询</Button>
              <Button onClick={reset}>重置</Button>
            </Space>
          </Form>
        </Space>
      </Card>
      <Card>
        <div style={{ textAlign: 'right' }}>
          <Button type='primary' onClick={onOK}>新增</Button>
        </div>
        <Table dataSource={list} columns={columns} pagination={false} />
        <Pagination defaultCurrent={1} total={total} style={{ marginTop: 30, textAlign: 'right' }} onChange={changePage} />
        {/* 新增弹出 */}
        <Modal title="新增城市" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
          <Form
            name="basic"
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
            autoComplete="off"
            form={form2}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
          >
            <Form.Item
              label="城市"
              name="city"
              rules={[{ required: true, message: 'Please input your city!' }]}
            >
              <Select allowClear>
                {
                  cityList.map((item) =>
                    <Select.Option key={item.id} value={item.nm}>{item.nm}</Select.Option>)
                }
              </Select>
            </Form.Item>
            <Form.Item
              name="useCar"
              label="用车模式"
              rules={[{ required: true, message: 'Please input your useCar!' }]}
            >
              <Select allowClear>
                <Select.Option value="1">禁停区</Select.Option>
                <Select.Option value="2">停车点</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item
              name="operating"
              label="运营模式"
              rules={[{ required: true, message: 'Please input your operating!' }]}
            >
              <Select allowClear>
                <Select.Option value="1">直营</Select.Option>
                <Select.Option value="2">加盟</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item
              name="admin"
              label="管理员"
              rules={[{ required: true, message: 'Please input your name!' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="openTime"
              label="开通时间"
              rules={[{ required: true, message: 'Please input your openTime!' }]}
            >
              <DatePicker />
            </Form.Item>

          </Form>
        </Modal>
      </Card>
    </Space>
  )
}
export default City;